﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using YeqianFramework.core;

namespace Assets.Scripts.UI
{
	[RequireComponent(typeof(Slider))]
	[ExecuteInEditMode]
	public class LoadingSlider : MonoBehaviour
	{
		private Slider m_slider;
		private Image sliderBG;
		private Text m_text;
		private float targetValue;
		[SerializeField]
		private float sliderSpeed;
		public bool isSliding = false;

		[SerializeField]
		private Color startColor;
		[SerializeField]
		private Color endColor;

		public float Value { get { return m_slider.value; } }

		private void Awake()
		{
			m_slider = GetComponent<Slider>();
			m_text = GetComponentInChildren<Text>();
			sliderBG = GetComponentInChildren<Image>();

			m_slider.onValueChanged.AddListener(val =>
			{
				m_text.text = "文明的种子正在重启：" + ((int)(val * 100)).ToString() + "%";
				//m_text.text = "文明的种子正在重启：" + val;
				sliderBG.color = Color.Lerp(startColor, endColor, m_slider.value / m_slider.maxValue);
			});
		}

		/// <summary>
		/// 范围 0~1
		/// </summary>
		/// <param name="val"></param>
		public void SetValue(float val)
		{
			isSliding = true;
			targetValue = val * m_slider.maxValue;
		}

		private void Update()
		{
			if (isSliding)
			{
				m_slider.value = Mathf.Lerp(m_slider.value, targetValue, sliderSpeed * Time.deltaTime);
				if (Mathf.Abs(m_slider.value - targetValue) < m_slider.maxValue * 0.05f)//进度条满了
				{
					isSliding = false;
					if (targetValue == m_slider.maxValue)
						MessageCenter.Current.SendMyMessage(UIEventType.LoadingSliderComplete, new YeqianFramework.common.KeyValuePair(gameObject.name, null));
				}
			}
		}
	}
}
